/**
 * FileName: LoginInterceptor
 * Author: Mr.Wang
 * Date: 2025/10/17 14:03
 * Description:
 * History:
 */
package org.test.device.config.jwt;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.test.device.utils.ResultData;
import org.test.device.utils.UserThreadLocal;

import java.io.PrintWriter;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Mr.Wang
 * @create 2025/10/17
 * @since 1.0.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求头获取Access Token（格式：Authorization: Bearer xxx-xxx-xxx）
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return sendUnAuthResponse(response, "请先登录");
        }

        // 2. 提取Token（去掉"Bearer "前缀）
        String accessToken = authHeader.substring(7);

        // 3. 验证Access Token有效性
        if (!jwtUtils.validateAccessToken(accessToken)) {
            return sendUnAuthResponse(response, "Access Token无效或已过期");
        }

        // 4. 解析Token获取用户ID，存入ThreadLocal（供后续接口使用）
        Long userId = jwtUtils.getUserIdFromAccessToken(accessToken);
        UserThreadLocal.set(userId); // 自定义ThreadLocal：存储当前登录用户ID

        // 5. 验证通过，放行接口
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove(); // 清除ThreadLocal
    }

    private boolean sendUnAuthResponse(HttpServletResponse response, String msg) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401状态码
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(new ResultData(msg)));
        out.flush();
        out.close();
        return false;
    }
}